//
//  AddManagerViewController.m
//  HandheldHospital
//
//  Created by zhangchao on 16/3/3.
//  Copyright © 2016年 zhangchao. All rights reserved.
//

#import "AddManagerViewController.h"
#import "DataCell.h"
#import "MyInputView.h"
#import <Masonry.h>
#import <AVOSCloud/AVOSCloud.h>
#import "PatientData.h"

#define kWidth self.tableView.frame.size.width
#define kHeight self.tableView.frame.size.height



@interface AddManagerViewController ()<UIPickerViewDelegate,UIPickerViewDataSource>
@property (nonatomic,strong) NSArray *sexArray;
@property (nonatomic,strong) NSArray *documentArray;
@property (nonatomic,strong) NSArray *cityArray;
@property (nonatomic,strong) NSArray *contentArray;
@property (nonatomic,strong) NSArray *placeholderArray;
@property (nonatomic,strong) MyInputView *myInputV;
@end


@implementation AddManagerViewController

- (NSArray *)cityArray
{
    if(_cityArray == nil)
    {
        _cityArray = [NSArray arrayWithObjects:@"北京市",@"天津市",@"上海市",@"重庆市",@"河北省",@"山西省",@"江苏省",@"浙江省",@"安徽省",@"福建省",@"江西省",@"山东省",@"河南省",@"湖北省",@"湖南省",@"广东省",@"辽宁省",@"吉林省",@"黑龙江省",@"广西壮族自治区",@"海南省",@"台湾省",@"四川省",@"贵州省",@"云南省",@"西藏自治区",@"陕西省",@"甘肃省",@"青海省",@"宁夏回族自治区",@"内蒙古自治区",@"新疆维吾尔自治区",@"香港特别行政区",@"澳门特别行政区", nil];
    }
    return _cityArray;
}

//懒加载,证件类型的数组
- (NSArray *)documentArray
{
    if(_documentArray == nil)
    {
        _documentArray = [NSArray arrayWithObjects:@"身份证",@"护照",@"港澳通行证",@"军官证", nil];
    }
    return _documentArray;
}

//懒加载，性别类型的数组
- (NSArray *)sexArray
{
    if(_sexArray == nil)
    {
        _sexArray = [NSArray arrayWithObjects:@"男",@"女", nil];
    }
    return _sexArray;
}

//懒加载,label名的数组
- (NSArray *)contentArray
{
    if(_contentArray == nil)
    {
        _contentArray = [NSArray arrayWithObjects:@"真实姓名",@"性别",@"出生日期",@"证件类型",@"证件号码",@"手机号",@"所在城市(选填)", nil];
    }
    return _contentArray;
}

//懒加载，占位符的数组
- (NSArray *)placeholderArray
{
    if(_placeholderArray == nil)
    {
        _placeholderArray = [NSArray arrayWithObjects:@"请输入姓名",@"请选择",@"请选择",@"请选择",@"请输入证件号码",@"请输入手机号码",@"请选择", nil];
    }
    return _placeholderArray;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self.myInputV removeFromSuperview];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.backgroundColor = [UIColor whiteColor];
    if(self.patient == nil)
    {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(saveAction)];
    }
    [self.tableView registerClass:[DataCell class] forCellReuseIdentifier:@"Cell"];
}

- (void)addMyInputView:(NSInteger)index;
{
    self.myInputV = [[MyInputView alloc] initWithFrame:CGRectMake(0, kHeight, kWidth, 0)];
    [self.navigationController.view addSubview:self.myInputV];
    self.myInputV.saveBtn.tag = 300 + index;
    [self.myInputV.saveBtn addTarget:self action:@selector(didClickSaveBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.myInputV.cancelBtn addTarget:self action:@selector(didClickCancelBtn:) forControlEvents:UIControlEventTouchUpInside];
}

//保存按钮事件
- (void)saveAction
{
    DataCell *cell0 = [self.tableView viewWithTag:200];
    DataCell *cell1 = [self.tableView viewWithTag:201];
    DataCell *cell2 = [self.tableView viewWithTag:202];
    DataCell *cell3 = [self.tableView viewWithTag:203];
    DataCell *cell4 = [self.tableView viewWithTag:204];
    DataCell *cell5 = [self.tableView viewWithTag:205];
    DataCell *cell6 = [self.tableView viewWithTag:206];
    NSString *str0 = cell0.contentTF.text;
    NSString *str1 = cell1.label.text;
    NSString *str2 = cell2.label.text;
    NSString *str3 = cell3.label.text;
    NSString *str4 = cell4.contentTF.text;
    NSString *str5 = cell5.contentTF.text;
    NSString *str6 = cell6.label.text;
    if(str0.length == 0)
    {
        [self showLabelWithString:@"请输入真实姓名" AndBlock:nil];
    }
    else if([str1 isEqualToString:@"请选择"])
    {
        [self showLabelWithString:@"请选择性别" AndBlock:nil];
    }
    else if([str2 isEqualToString:@"请选择"])
    {
        [self showLabelWithString:@"请选择出生日期" AndBlock:nil];
    }
    else if([str3 isEqualToString:@"请选择"])
    {
        [self showLabelWithString:@"请选择证件类型" AndBlock:nil];
    }
    else if(str4.length == 0)
    {
        [self showLabelWithString:@"请输入证件号码" AndBlock:nil];
    }
    else if(str5.length == 0)
    {
        [self showLabelWithString:@"请输入手机号码" AndBlock:nil];
    }
    else if([str6 isEqualToString:@"请选择"])
    {
        [self showLabelWithString:@"请选择所在城市" AndBlock:nil];
    }
    else
    {
        PatientData *patient = [PatientData object];
        patient.currentUser = [AVUser currentUser];
        patient.name = str0;
        patient.sex = str1;
        patient.birthdate = str2;
        patient.documentType = str3;
        patient.documentId = str4;
        patient.phoneNumber = str5;
        patient.city = str6;
        [patient saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if(succeeded)
            {
                NSLog(@"成功");
                [self.navigationController popViewControllerAnimated:YES];
            }
            else
            {
                NSLog(@"失败");
            }
        }];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.contentArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DataCell *cell = [DataCell cellWithTableView:tableView];
    if(self.patient != nil)
    {
        cell.contentLabel.text = self.contentArray[indexPath.row];
        if(indexPath.row == 0)
        {
            cell.contentTF.hidden = NO;
            cell.label.hidden = YES;
            cell.contentTF.text = self.patient.name;
            return cell;
        }
        if(indexPath.row == 1)
        {
            cell.contentTF.hidden = YES;
            cell.label.hidden = NO;
            cell.label.text = self.patient.sex;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return cell;
        }
        if(indexPath.row == 2)
        {
            cell.contentTF.hidden = YES;
            cell.label.hidden = NO;
            cell.label.text = self.patient.birthdate;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return cell;
        }
        if(indexPath.row == 3)
        {
            cell.contentTF.hidden = YES;
            cell.label.hidden = NO;
            cell.label.text = self.patient.documentType;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return cell;
        }
        if(indexPath.row == 4)
        {
            cell.contentTF.hidden = NO;
            cell.label.hidden = YES;
            cell.contentTF.text = self.patient.documentId;
            return cell;
        }
        if(indexPath.row == 5)
        {
            cell.contentTF.hidden = NO;
            cell.label.hidden = YES;
            cell.contentTF.text = self.patient.phoneNumber;
            return cell;
        }
        if(indexPath.row == 6)
        {
            cell.contentTF.hidden = YES;
            cell.label.hidden = NO;
            cell.label.text = self.patient.city;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return cell;
        }
    }
    else
    {
        cell.contentLabel.text = self.contentArray[indexPath.row];
        if(indexPath.row == 1 || indexPath.row == 2 || indexPath.row == 3 || indexPath.row == 6)
        {
            
            cell.label.textColor = [UIColor grayColor];
            cell.label.hidden = NO;
            cell.contentTF.hidden = YES;
            cell.label.text = self.placeholderArray[indexPath.row];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            if(indexPath.row == 1)
            {
                cell.tag = 201;
            }
            if(indexPath.row == 2)
            {
                cell.tag = 202;
            }
            if(indexPath.row == 3)
            {
                cell.tag = 203;
            }
            if(indexPath.row == 6)
            {
                cell.tag = 206;
            }
        }
        else
        {
            cell.contentTF.hidden = NO;
            cell.label.hidden = YES;
            cell.contentTF.placeholder = self.placeholderArray[indexPath.row];
            if(indexPath.row == 0)
            {
                cell.tag = 200;
            }
            if(indexPath.row == 4)
            {
                cell.tag = 204;
            }
            if(indexPath.row == 5)
            {
                cell.tag = 205;
            }
        }
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DataCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if(indexPath.row == 0 || indexPath.row == 4 || indexPath.row == 5)
    {
        [self.myInputV removeFromSuperview];
        [cell.contentTF becomeFirstResponder];
        if(indexPath.row == 4 || indexPath.row == 5)
        {
            cell.contentTF.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        }
    }
    else if(indexPath.row == 1)
    {
        [self.myInputV removeFromSuperview];
        [self addMyInputView:indexPath.row];
        [self addPickerView:indexPath.row];
        [self addAnimation];
        
    }else if(indexPath.row == 2)
    {
        [self.myInputV removeFromSuperview];
        [self addMyInputView:indexPath.row];
        [self addDataPicker:indexPath.row];
        [self addAnimation];
        
    }else if(indexPath.row == 3)
    {
        [self.myInputV removeFromSuperview];
        [self addMyInputView:indexPath.row];
        [self addPickerView:indexPath.row];
        [self addAnimation];
        
    }else if(indexPath.row == 6)
    {
        [self.myInputV removeFromSuperview];
        [self addMyInputView:indexPath.row];
        [self addPickerView:indexPath.row];
        [self addAnimation];
    }
}

- (void)addDataPicker:(NSInteger)row;
{
    UIDatePicker *datePick = [[UIDatePicker alloc] init];
    [datePick setDatePickerMode:UIDatePickerModeDate];
    datePick.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CH"];
    [datePick addTarget:self action:@selector(dateChage:) forControlEvents:UIControlEventValueChanged];
    [self.myInputV addSubview:datePick];
    [datePick mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.myInputV).offset(35);
        make.left.equalTo(self.myInputV).offset(0);
        make.right.equalTo(self.myInputV).offset(0);
    }];
}

//添加pickerView到InputView上
- (void)addPickerView:(NSInteger)row;
{
    UIPickerView *pickerV = [[UIPickerView alloc] init];
    pickerV.backgroundColor = [UIColor whiteColor];
    pickerV.delegate = self;
    pickerV.dataSource = self;
    pickerV.tag = (100 + row);
    [self.myInputV addSubview:pickerV];
    [pickerV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.myInputV).offset(35);
        make.left.equalTo(self.myInputV).offset(0);
        make.right.equalTo(self.myInputV).offset(0);
    }];
}


//推出动画
- (void)addAnimation
{
    //每次推出pickerView时先退出键盘
    DataCell *cell1 = [self.tableView viewWithTag:200];
    DataCell *cell2 = [self.tableView viewWithTag:204];
    DataCell *cell3 = [self.tableView viewWithTag:205];
    [cell1.contentTF resignFirstResponder];
    [cell2.contentTF resignFirstResponder];
    [cell3.contentTF resignFirstResponder];
    
    [UIView beginAnimations:nil context:nil];
    //设置动画持续时间
    [UIView setAnimationDuration:0.1];
    self.myInputV.frame = CGRectMake(0, kHeight * 0.6,kWidth , kHeight * 0.4);
    //动画提交
    [UIView commitAnimations];
}

//退出动画
- (void)endAnimation
{
    [UIView beginAnimations:nil context:nil];
    //设置动画持续时间
    [UIView setAnimationDuration:0.1];
    self.myInputV.frame = CGRectMake(0, kHeight ,kWidth , 0);
    //动画提交
    [UIView commitAnimations];
}

- (void)didClickCancelBtn:(UIButton *)sender
{
    [self endAnimation];
}

- (void)didClickSaveBtn:(UIButton *)sender
{
    
    [self endAnimation];
}

#pragma mark pickerView代理方法

//设置pickerView组件的个数 （即滚轮个数）
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
//设置组件里的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if(pickerView.tag == 101)
    {
        return 2;
        
    }
    if(pickerView.tag == 103)
    {
        return 4;
    }
    if(pickerView.tag == 106)
    {
        return self.cityArray.count;
    }
    return 0;
}

//滚轮显示的内容
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if(pickerView.tag == 101)
    {
        DataCell *cell = [self.tableView viewWithTag:201];
        cell.label.text = self.sexArray[row];
        cell.label.textColor = [UIColor blackColor];
        return self.sexArray[row];
    }
    if(pickerView.tag == 103)
    {
        DataCell *cell = [self.tableView viewWithTag:203];
        cell.label.text = self.documentArray[row];
        cell.label.textColor = [UIColor blackColor];
        return self.documentArray[row];
    }
    if(pickerView.tag == 106)
    {
        DataCell *cell = [self.tableView viewWithTag:206];
        cell.label.text = self.cityArray[row];
        cell.label.textColor = [UIColor blackColor];
        return self.cityArray[row];

    }
    return nil;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if(pickerView.tag == 101)
    {
        DataCell *cell = [self.tableView viewWithTag:201];
        cell.label.text = self.sexArray[row];
        cell.label.textColor = [UIColor blackColor];
    }
    if(pickerView.tag == 103)
    {
        DataCell *cell = [self.tableView viewWithTag:203];
        cell.label.text = self.documentArray[row];
        cell.label.textColor = [UIColor blackColor];
    }
    if(pickerView.tag == 106)
    {
        DataCell *cell = [self.tableView viewWithTag:206];
        cell.label.text = self.cityArray[row];
        cell.label.textColor = [UIColor blackColor];
    }
}


//获取datapicker上显示的时间数据
- (void)dateChage:(UIDatePicker *)picker
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *firstTime = [formatter stringFromDate:picker.date];
    NSString *secondTime = [formatter stringFromDate:[NSDate date]];
    if([firstTime compare:secondTime] > 0)
    {
        [self showLabelWithString:@"请选择正确的出生日期" AndBlock:nil];
    }
    else
    {
        DataCell *cell = [self.tableView viewWithTag:202];
        cell.label.textColor = [UIColor blackColor];
        cell.label.text = [formatter stringFromDate:picker.date];
    }
    
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
